import React from 'react';
import { inject, observer } from 'mobx-react';
import {
  WeaDialog,
  WeaUpload,
  WeaPopoverHrm,
  WeaNewScrollPagination,
  WeaBrowser,
  WeaNewScroll,
  WeaLocaleProvider,
} from 'ecCom';
import { Button, Row, Col, Icon, Progress, Modal } from 'antd';
import { toJS } from 'mobx';

const warning = Modal.warning;
// const Item = Menu.Item;
const store = [
  'docCenterStore',
  'routing',
];
const getLabel = WeaLocaleProvider.getLabel;
@inject(...store)

@observer
class CenterLeft extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      hasMore: true,
      // ----- upload
      category: '',
      categoryName: [],
      visibleUpload: false,
      isShowCheckInfo: false, // false 表示文件上传目录为空
      uploadFileList: [],
      hadForDocList: [],
      uploadShowListT: [],
      uploadShowListB: [],
      uploadStatus: '',
      // ----- upload
      visibleReply: false,
      dialogReply: {
        title: getLabel(385101, '收到的评论和点赞'),
        icon: 'icon-coms-doc',
        iconBgcolor: '#F14A2D',
        style: { width: '736px' },
        // buttons:[(<Button>更多</Button>)],
      },
      dialogUpload: {
        title: getLabel(30899, '上传文档'),
        icon: 'icon-coms-doc',
        iconBgcolor: '#F14A2D',
        style: { width: '600px', height: '510px' },
      },
      newScrollPagination: {
        height: 440,
      },
      isLoadingShow: false,
      browser: {
        type: 'doccategory',
        title: getLabel(385103, '可新建文档的目录'),
        icon: 'icon-coms-doc',
        iconBgcolor: '#F14A2D',
        inputStyle: {
          width: '517px',
          height: '39px',
          marginTop: '32px',
          marginLeft: '30px',
        },
        tabs: [
          {
            key: '1',
            name: getLabel(385079, '全部目录'),
            url: '/api/public/browser/data/doccategory',
            dataParams: { iscreate: 1, isFav: 0, isCommon: 0 },
          },
          {
            key: '2',
            name: getLabel(18030, '我的收藏'),
            url: '/api/public/browser/data/doccategory',
            dataParams: { iscreate: 1, isFav: 1, isCommon: 0 },
          },
          {
            key: '3',
            name: getLabel(28183, '常用目录'),
            url: '/api/public/browser/data/doccategory',
            dataParams: { iscreate: 1, isFav: 0, isCommon: 1 },
          },
        ],
        quickSearchName: 'categoryname',
        completeParams: { iscreate: 1 },
      },
    };
  }

  componentDidMount() {

  }

  componentWillReceiveProps() {
  }

  componentWillUnmount() {
  }

  getUploadList() {
    const {
      isShowCheckInfo, uploadFileList, uploadStatus, categoryName,
      uploadShowListT, uploadShowListB,
    } = this.state;
    if (!isShowCheckInfo || !uploadStatus || uploadStatus === 'false') {
      return (
        <p style={{ height: 187 }}>
          <img src="/spa/document/images/uploadFileType.png"
            style={{ marginTop: 110 }}
          />
        </p>
      );
    } else if (uploadStatus === 'uploaded') {
      return (
        <div style={{ width: '100%' }}>
          <i className="icon-coms-Upload-successfully"
            style={{ fontSize: 55, marginTop: 93, display: 'inline-block', color: '#2db7f5' }}
          />
          <p style={{ margin: '22px 0 24px', color: '#999' }}>
            <span>{getLabel(127883, '成功上传')}</span>
            <strong style={{ fontSize: 18, color: '#48C0F6' }}>{uploadFileList.length}</strong>
            <span> {getLabel(127884, '篇文档到')}</span>
            <span style={{ color: '#48C0F6' }}>{categoryName}</span>
          </p>
        </div>
      );
    }
    const arr = [];
    uploadShowListT.forEach((item) => {
      const {
        imgSrc, filelink, filename,
        filesize, loadlink, isImg,
      } = item;
      arr.push(
        <div className="wea-upload-list-item">
          <div className="wea-upload-list-item-file wea-upload-list-item-file-t"
            style={{
              height: 50,
              padding: '10px 180px 10px 0',
              borderBottom: '1px solid #dadada',
            }}
          >
            <img src={imgSrc} style={{ width: 16, height: 16 }} />
            {
              isImg ?
                <a title={filename}
                  onClick={() => {
                  }}
                  className="formImgPlay wea-field-link"
                  src={filelink}
                  data-imgsrc={loadlink}
                >{filename}</a>
                :
                <a title={filename}
                  onClick={() => {
                  }}
                  className="wea-field-link"
                >{filename}</a>
            }
            {
              <div className="wea-upload-list-item-filesize"
                style={{ width: 175, paddingTop: 10 }}
              >
                <span style={{ color: '#999', marginLeft: 8 }}>{filesize}</span>
                <span style={{ color: '#6dce76', float: 'right' }}>
                  {getLabel(25388, '上传成功')}
                  <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@qmrg6m@check`} type="check" style={{ marginLeft: 5 }} />
                </span>
              </div>
            }
          </div>
        </div>,
      );
    });
    uploadShowListB.forEach((item) => {
      const { name, progress, showProgress, error, progressStatus } = item;
      const status = error && progressStatus ? { status: progressStatus } : {};
      arr.push(
        <div className="wea-upload-list-item">
          <div className="wea-upload-list-item-file wea-upload-list-item-file-b"
            style={error ? { padding: '0 110px 0 0' } : {}}
          >
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@1g55ms@paper-clip`} type="paper-clip" style={{ marginRight: 5 }} />
            {name}
            {error &&
              <span style={{
                display: 'inline-block',
                color: '#f00',
                position: 'absolute',
                right: 40,
                top: 0,
              }}
              >{`（${error}）`}</span>
            }
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@wi0lv2@"Delete"`} type="cross"
              className="wea-upload-list-item-del"
              style={{ fontSize: 10 }}
              title={getLabel(91, '删除')}
              onClick={() => {
              }}
            />
          </div>
          {showProgress &&
            <Progress ecId={`${this && this.props && this.props.ecId || ''}_Progress@ov7155@Progress`} percent={progress} strokeWidth={3} {...status} />
          }
        </div>,
      );
    });
    return (
      <div className="wea-upload" style={{ padding: '0 20px' }}>
        <div className="wea-upload-list" style={{ textAlign: 'left', paddingBottom: 52 }}>
          {arr}
        </div>
      </div>
    );
  }

  getUpload() {
    const { docCenterStore } = this.props;
    const {
      isShowCheckInfo, uploadStatus, uploadShowListB, uploadFileList,
      category,
    } = this.state;
    const { uploadSet, accForDoc } = docCenterStore;
    const pre = 'wea-doc-center-left-upload';
    if (!isShowCheckInfo || !uploadSet || uploadSet.maxUploadSize <= 0) {
      return (
        <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@1zzmuk`} disabled
          className={`${pre}-uploading-btn`}
          type="primary"
          style={{ width: 158 }}
        >
          <span className="icon-coms-upload" />
          {getLabel(30899, '上传文档')}
        </Button>
      );
    }
    const isUploading = uploadStatus === 'uploading';
    return (
      <div className={`${pre} ${
        isUploading ? `${pre}-uploading` : ''}`}
      >
        <WeaUpload ecId={`${this && this.props && this.props.ecId || ''}_WeaUpload@4ny6jt`}
          ref={ref => this.upload = ref}
          {...toJS(uploadSet)}
          datas={uploadFileList}
          onChange={(ids, list) => {
            this.setState({
              uploadFileList: list,
              hadForDocList: uploadFileList.map(file => file.fileid),
            });
          }}
          uploadParams={{ secCategory: category }}
          onUploading={(status) => {
            this.setState({ uploadStatus: status });
            if (status === 'uploaded') {
              const { hadForDocList } = this.state;
              uploadFileList.forEach((item) => {
                hadForDocList.indexOf(item.fileid) < 0
                  && accForDoc({ secid: category, fileid: item.fileid });
              });
            }
          }}
          getShowListDatas={(listT, listB) => {
            this.setState({
              uploadShowListT: listT,
              uploadShowListB: listB,
            });
          }}
        >
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qn84g7`} className={`${pre}-uploading-btn`}
            type={isUploading ? 'ghost' : 'primary'}
          >
            <i className="icon-coms-upload" />
            {!uploadStatus || uploadStatus === 'false' ? getLabel(30899, '上传文档') : getLabel(81561, '继续上传')}
          </Button>
        </WeaUpload>
        {isUploading &&
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@e7d3qg`} className={`${pre}-uploading-btn-cancel`}
            type="ghost"
            disabled={uploadShowListB.length === 0}
            onClick={() => {
              // console.log(this.upload);
              this.upload.cancleUpload();
              // this.upload.clearAllFiles();
            }}
          >
            <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@ld8mzd`} type="cross" />
            {getLabel(129226, '全部取消')}
          </Button>
        }
      </div>
    );
  }

  render() {
    const { docCenterStore, routing } = this.props;
    const {
      userInfo, numOfAll, numOfMy, numOfReplyAndPraise
      , rankDepartment, rankSubDepartment, rankHead
      , lastestReader, numOfReplyAndPraiseDetail
      , numOfReplyAndPraiseDetailData
      , getNumOfReplyAndPraiseDetail
      , getNumOfReplyAndPraise, getUploadSet
      , uploadSet
      , categoryDatas
      , setCategoryDatas,
    } = docCenterStore;
    const {
      visibleUpload, dialogUpload
      , isShowCheckInfo, category
      , visibleReply, dialogReply, newScrollPagination
      , isLoadingShow, browser,
    } = this.state;
    const user = toJS(userInfo);
    const numOfReplyAndPraiseDetails = toJS(numOfReplyAndPraiseDetail);
    const lastestReaderContent = lastestReader.slice().map((item, ind) => (
      <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@6sco8r@${ind}`} span={6}>
        <img src={`${item.userphoto}`} className="centerleft-reader-img" />
        <div>
          <a href={`javaScript:openhrm(${item.userid});`}
            onClick={() => window.pointerXY(event)}
            title={`${item.username}`}
          >
            {item.username}
          </a>
        </div>
      </Col>
    ));
    const newScrollDataContent = (
      <ul>
        {
          numOfReplyAndPraiseDetailData.map((item, index) => {
            if (index === numOfReplyAndPraiseDetailData.length - 1) {
              return (
                <li className="centerleft-reply-end">
                  <img className="centerleft-reply-img" src={`${item.photoUrl}`} />
                  <ul className="centerleft-reply-ul">
                    <li>
                      <a className="reply-hrm"
                        href={`javaScript:openhrm(${item.prid});`}
                        onClick={e => window.pointerXY(e)}
                        title={item.username}
                      >{item.username}</a>
                      <span className="centerleft-reply-span centerleft-reply-color">
                        {item.dateTime}
                      </span>
                      <span className="centerleft-reply-span">{getLabel(31505, '来自')}</span>
                      <a className="centerleft-reply-span center-reply-docname"
                        onClick={() =>
                          window.open(
                            `/spa/document/index.jsp?id=${item.docid}#/main/document/detail`,
                          )
                        }
                      >{item.docname}</a>
                    </li>
                    {
                      item.diff === '0' ? (
                        <li className="centerleft-reply-li ">
                          <span dangerouslySetInnerHTML={{ __html: item.content }} />
                        </li>
                      ) : (
                          <li className="centerleft-reply-li centerleft-reply-color">
                            <span dangerouslySetInnerHTML={{ __html: item.content }} />
                          </li>
                        )
                    }
                  </ul>
                </li>
              );
            }
            return (
              <li className="centerleft-reply">
                <img className="centerleft-reply-img" src={`${item.photoUrl}`} />
                <ul className="centerleft-reply-ul">
                  <li>
                    <a className="reply-hrm"
                      href={`javaScript:openhrm(${item.prid});`}
                      onClick={e => window.pointerXY(e)}
                      title={item.username}
                    >{item.username}</a>
                    <span className="centerleft-reply-span centerleft-reply-color">
                      {item.dateTime}
                    </span>
                    <span className="centerleft-reply-span">{getLabel(31505, '来自')}</span>
                    <a className="centerleft-reply-span center-reply-docname"
                      onClick={() =>
                        window.open(
                          `/spa/document/index.jsp?id=${item.docid}#/main/document/detail`,
                        )
                      }
                    >{item.docname}</a>
                  </li>
                  {
                    item.diff === '0' ? (
                      <li className="centerleft-reply-li ">
                        <span dangerouslySetInnerHTML={{ __html: item.content }} />
                      </li>
                    ) : (
                        <li className="centerleft-reply-li centerleft-reply-color">
                          <span dangerouslySetInnerHTML={{ __html: item.content }} />
                        </li>
                      )
                  }
                </ul>
              </li>
            );
          })
        }
        {isLoadingShow && numOfReplyAndPraiseDetails
          && numOfReplyAndPraiseDetails.hasMore && (
            <li>
              <div className="centerleft-reply-loading">
                {getLabel(31153, '数据加载中，请稍等...')},
            </div>
            </li>
          )
        }
        {isLoadingShow && numOfReplyAndPraiseDetails
          && !numOfReplyAndPraiseDetails.hasMore && (
            <li>
              <div className="centerleft-reply-loading">
                {getLabel(385098, '所有数据已经加载完成')}
              </div>
            </li>
          )
        }
      </ul>
    );
    return (
      <div>
        <div className="centerleft-user">
          <img className="centerleft-user-img" src={user.photoUrl} />
          <div>
            <a href={`javaScript:openhrm(${user.userId});`}
              onClick={() => window.pointerXY(event)}
              title={`${user.userName}`}
            >
              {user.userName}
            </a>
          </div>
          {
            location.pathname === '/spa/document/index_mobx.html' && (<WeaPopoverHrm ecId={`${this && this.props && this.props.ecId || ''}_WeaPopoverHrm@mb2n2r`} />)
          }
        </div>
        <ul className="centerleft-ul">
          <li onClick={() => {
            if (routing) {
              routing.push(
                {
                  pathname: '/main/document/search',
                  query: { viewcondition: '2' },
                  state: {
                    prePath: '/main/document/center',
                    prePathName: getLabel(132038, '知识中心'),
                  },
                },
              );
            }
          }}
          >
            <span>{getLabel(31875, '知识库')}</span>
            <span>{numOfAll.number}</span>
          </li>
          <li onClick={() => {
            if (routing) {
              routing.push(
                {
                  pathname: '/main/document/search',
                  query: { viewcondition: '0' },
                  state: {
                    prePath: '/main/document/center',
                    prePathName: getLabel(132038, '知识中心'),
                  },
                },
              );
            }
          }}
          >
            <span>{getLabel(1212, '我的文档')}</span>
            <span>{numOfMy.number}</span>
          </li>
          <li onClick={() => {
            // if (numOfReplyAndPraiseDetails.hasMore) getNumOfReplyAndPraiseDetail();
            this.setState({ visibleReply: true }, () => {
              getNumOfReplyAndPraise();
              getNumOfReplyAndPraiseDetail({}, true);
            });
          }}
          >
            <span className="centerleft-span">{getLabel(385101, '收到的评论和点赞')}
              {numOfReplyAndPraise.hasNew && (
                <sup className="centerleft-sup"
                  style={{ fontSize: '50px', color: '#E83704' }}
                >.</sup>)}
            </span>
            <span>
              {numOfReplyAndPraise.number}
            </span>
          </li>
        </ul>
        <div className="centerleft-ranking">
          <div className="centerleft-icon-container"><span>|</span>{getLabel(385092, '贡献排名')}</div>
          <div className="centerleft-ranking-content"
            onClick={() => {
              if (routing) {
                routing.push(
                  {
                    pathname: '/main/document/docofauthor',
                    query: {
                      deptType: '3',
                      dept_id: user.userDept,
                      doccreatedateselect: '3',
                      statusType: '2',
                    },
                    state: {
                      prePath: '/main/document/center',
                      prePathName: getLabel(132038, '知识中心'),
                    },
                  },
                );
              }
            }}
          >
            <span>{getLabel(385093, '部门排名')}:</span>
            <span>{rankDepartment.number}</span>
            <span className="icon-document-Ranking" />
          </div>
          <div className="centerleft-ranking-content"
            onClick={() => {
              if (routing) {
                routing.push(
                  {
                    pathname: '/main/document/docofauthor',
                    query: {
                      deptType: '2',
                      branch_id: user.userSubsection,
                      doccreatedateselect: '3',
                      statusType: '2',
                    },
                    state: {
                      prePath: '/main/document/center',
                      prePathName: getLabel(132038, '知识中心'),
                    },
                  },
                );
              }
            }}
          >
            <span>{getLabel(385094, '分部排名')}:</span>
            <span>{rankSubDepartment.number}</span>
            <span className="icon-document-Ranking" />
          </div>
          <div className="centerleft-ranking-content"
            onClick={() => {
              if (routing) {
                routing.push(
                  {
                    pathname: '/main/document/docofauthor',
                    query: {
                      deptType: '1',
                      doccreatedateselect: '3',
                      statusType: '2',
                    },
                    state: {
                      prePath: '/main/document/center',
                      prePathName: getLabel(132038, '知识中心'),
                    },
                  },
                );
              }
            }}
          >
            <span>{getLabel(385095, '总部排名')}:</span>
            <span>{rankHead.number}</span>
            <span className="icon-document-Ranking" />
          </div>
        </div>
        <div className="centerleft-btn">
          <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@fzpu5e`} className="centerleft-btn-upload"
            type="primary"
            onClick={() => {
              this.setState({ visibleUpload: true });
            }}
          >
            <i className="icon-coms-upload" />
            <span style={{ paddingLeft: 10 }}>{getLabel(30899, '上传文档')}</span>
          </Button>
        </div>
        <div className="centerleft-reader">
          <div className="centerleft-icon-container"><span>|</span>{getLabel(385096, '最近读者')}</div>
          <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@8ptphq`}>
            {lastestReaderContent}
          </Row>
        </div>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@zoksyu`}
          className="wea-doc-center-left-upload"
          visible={visibleUpload}
          {...dialogUpload}
          onCancel={() => {
            this.setState({
              visibleUpload: false,
              uploadFileList: [],
              uploadShowListT: [],
              uploadShowListB: [],
              uploadStatus: '',
              hadForDocList: [],
              isShowCheckInfo: false,
            });
          }}
          buttons={
            [
              <span
                style={{
                  display: 'inline-block',
                  margin: '4px 0 4px 10px',
                  color: '#999',
                  cursor: 'pointer',
                }}
                onClick={() => {
                  if (!isShowCheckInfo) {
                    warning({
                      content: `${getLabel(33252, '请先选择目录')}！`,
                    });
                  } else if (!uploadSet || uploadSet.maxUploadSize <= 0) {
                    warning({
                      content: getLabel(385097, '此目录不允许上传附件，请重新选择目录！'),
                    });
                  } else {
                    window.open(
                      `/spa/document/index.jsp?secid=${category}`
                      + '&isEdit=1&router=1#/main/document/edit',
                    );
                  }
                }}
              >{getLabel(385104, '完整模式')}>></span>,
            ]
          }
          style={{ width: 652, height: 461 }}
        >
          <div className="wea-doc-center-uploadfile">
            <WeaBrowser ecId={`${this && this.props && this.props.ecId || ''}_WeaBrowser@dyrldj`} {...browser}
              viewAttr="3"
              onChange={(ids, name, datas) => {
                if (ids === '') {
                  this.setState({ isShowCheckInfo: false, uploadFileList: [], uploadStatus: '' });
                  setCategoryDatas(datas);
                } else {
                  this.setState({
                    isShowCheckInfo: true,
                    category: ids,
                    categoryName: name,
                    uploadStatus: '',
                  });
                  getUploadSet({ secid: ids });
                  setCategoryDatas(datas);
                }
              }}
            // replaceDatas={categoryDatas}
            />
            {
              !isShowCheckInfo ? (<div className="centerleft-upload-tip">{getLabel(33252, '请先选择目录')}</div>) : (
                <div className="centerleft-upload-tipl">
                  {
                    uploadSet && uploadSet.maxUploadSize > 0
                      ? <span>{getLabel(385099, '此目录下最大上传')}{uploadSet.maxUploadSize}{getLabel(385100, 'M/个的附件')}{getLabel(506208, ',最小上传')}{uploadSet.mixUploadSize}{getLabel(385100, 'M/个的附件')}</span>
                      : <span className="centerleft-upload-noupload">{getLabel(385102, '目录不允许上传附件')}</span>
                  }
                </div>
              )
            }
          </div>
          <div className="wea-doc-center-centerleft-dialog"
            style={isShowCheckInfo ? {} : { backgroundColor: '#f9f9f9' }}
          >
            <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@u918ct`} height="100%">
              {this.getUploadList()}
              {this.getUpload()}
            </WeaNewScroll>
          </div>
        </WeaDialog>
        <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@fp6gqn`} visible={visibleReply}
          {...dialogReply}
          onCancel={() => this.setState({ visibleReply: false })}
          moreBtn={{
            collectParams: {
              favname: getLabel(385101, '收到的评论和点赞'),
              favouritetype: 2,
              objid: 0,
              importantlevel: 1,
            },
          }}
        >
          <WeaNewScrollPagination ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScrollPagination@xnaq4d`}
            {...newScrollPagination}
            onScrollEnd={() => {
              this.setState({ isLoadingShow: true }, () => {
                if (numOfReplyAndPraiseDetails.hasMore) {
                  getNumOfReplyAndPraiseDetail(
                    {
                      lastPraiseId: numOfReplyAndPraiseDetails.lastPraiseId,
                      lastReplyId: numOfReplyAndPraiseDetails.lastReplyId,
                    },
                  );
                  setTimeout(() => {
                    this.setState({
                      isLoadingShow: false,
                      hasMore: numOfReplyAndPraiseDetails.hasMore,
                    });
                  }, 2000);
                }
              });
            }}
          >
            <div className="wea-doc-center-centerleft-reply">
              {
                newScrollDataContent.length > 6 ? (
                  <div style={{ height: '750px' }}>
                    {newScrollDataContent}
                  </div>
                ) : (
                    <div style={{ height: '100%' }}>
                      {newScrollDataContent}
                    </div>
                  )
              }
            </div>
          </WeaNewScrollPagination>
        </WeaDialog>
      </div>
    );
  }
}

export default CenterLeft;
